package com.chookss;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.baidu.mobstat.StatService;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.bun.miitmdid.core.MdidSdkHelper;
import com.bun.supplier.IIdentifierListener;
import com.bun.supplier.IdSupplier;
import com.chookss.base.AppStatus;
import com.chookss.base.AppStatusManager;
import com.chookss.base.StaticClass;
import com.chookss.home.HomeFragmentss;
import com.chookss.home.HomeKnowledgeFragmentss;
import com.chookss.home.document.DocumentBaseFragment;
import com.chookss.home.entity.ContactEntity;
import com.chookss.home.entity.DocunmentEntity;
import com.chookss.home.entity.LogEntity;
import com.chookss.home.entity.UploadEntity;
import com.chookss.home.gallery.GalleryBaseFragment;
import com.chookss.home.gallery.PublishGalleryActivity;
import com.chookss.home.interview.InterviewBaseFragment;
import com.chookss.home.interview.InvitationRegisterActivity;
import com.chookss.home.knowledge.KnowledgeBaseFragment;
import com.chookss.home.logContacts.ContactsBaseFragment;
import com.chookss.home.logContacts.LookLogBaseFragment;
import com.chookss.home.myTest.TestBaseFragment;
import com.chookss.home.other.AbilityAnalyzeBaseFragment;
import com.chookss.home.other.NoticeBaseFragment;
import com.chookss.home.publish.PublishLogsActivity;
import com.chookss.home.publish.PublishNewsActivity;
import com.chookss.home.publish.PublishVedioActivity;
import com.chookss.home.rank.RankBaseFragment;
import com.chookss.home.studyPlan.StudyPlanBaseFragment;
import com.chookss.home.tuwen.NewsLinkActivity;
import com.chookss.home.tuwen.PublishTuwensActivity;
import com.chookss.home.tuwen.TuwenBaseFragment;
import com.chookss.home.tuwen.TuwenSearchActivity;
import com.chookss.home.update.InstallLocalApk;
import com.chookss.login.LoginQrCodeActivity;
import com.chookss.login.SplashActivity;
import com.chookss.mine.MineFragment;
import com.chookss.tiku.TikuFragments;
import com.chookss.tools.FileUtilss;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.PathUtil;
import com.chookss.tools.PermissionSpUtils;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.video.RecordFragment;
import com.chookss.video.VideoMainFragments;
import com.chookss.video.entity.VideoEntity;
import com.chookss.view.CircleImageView;
import com.chookss.view.ForScreenDialog;
import com.chookss.view.GlideEngine;
import com.chookss.view.HomeAdvertDialog;
import com.chookss.view.HomeBottomDialog;
import com.chookss.view.ImageFileCompressEngine;
import com.chookss.view.UpdateDialog;
import com.chookss.view.listener.HomeBottomDialogListener;
import com.chookss.view.listener.ShareDialogListener;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.luck.picture.lib.animators.AnimationType;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

/**
 * @author geyifeng
 * @date 2017/7/20
 */
public class HomeActivityss extends BaseAct implements View.OnClickListener, VideoMainFragments.OnFragmentInteractionListener {


    @BindView(R.id.content)
    FrameLayout content;
    @BindView(R.id.ll_bottom0)
    LinearLayout llBottom0;
    @BindView(R.id.ll_bottom1)
    LinearLayout llBottom1;
    @BindView(R.id.ivBottom1)
    ImageView ivBottom1;
    @BindView(R.id.tvNumBottom1)
    TextView tvNumBottom1;
    @BindView(R.id.tvNumBottom3)
    TextView tvNumBottom3;
    @BindView(R.id.ivBottom3)
    ImageView ivBottom3;
    @BindView(R.id.tvBottom1)
    TextView tvBottom1;
    @BindView(R.id.tvBottom3)
    TextView tvBottom3;
    @BindView(R.id.ll_bottom2_iv)
    CircleImageView llBottom2Iv;
    @BindView(R.id.ll_bottom2)
    LinearLayout llBottom2;
    @BindView(R.id.ll_bottom3)
    LinearLayout llBottom3;
    @BindView(R.id.ll_bottom4)
    LinearLayout llBottom4;
    @BindView(R.id.homeBottom)
    LinearLayout homeBottom;
    @BindView(R.id.line)
    View line;
    private Fragment bottomFragment0;
    private Fragment bottomFragment1;
    private Fragment bottomFragment3;
    private LookLogBaseFragment lookLogBaseFragment;
    private RecordFragment recordFragment;
    private MineFragment mineFragment;
    private int num = 0;//下标  从知识库主题过来的话，就是直接跳转某个具体下标
    private int index = 2; //视频模块默认选择中间那个
    private int GET_UNKNOWN_APP_SOURCES = 0x101;
    private String fileName = "", fileUrl = "";
    private String navigationCode1 = "13";//默认是13题库  03是资料库  14视频
    private String navigationName1 = "题库";//默认是13题库  03是资料库  14视频
    private String navigationCode3 = "14";//默认是13题库  03是资料库   14视频19也是
    private String navigationName3 = "视频";//默认是13题库  03是资料库   14视频
    private boolean isPublish = true;  //是否有发布权限
    private int newNum = -1;//知识库主题跳转专用
    private boolean isFirst = false;//当次启动是否是第一次进来  true是第一次，只有第一次才加载广告弹窗

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mainss);
        isFirst = getIntent().getBooleanExtra("isFirst", false);
        ButterKnife.bind(this);
        //特殊纪念日 主题变灰
        if(MyApp.THEME){
            Paint paint = new Paint();
            ColorMatrix cm = new ColorMatrix();
            cm.setSaturation(0);//灰度效果
            paint.setColorFilter(new ColorMatrixColorFilter(cm));
            getWindow().getDecorView().setLayerType(View.LAYER_TYPE_HARDWARE,paint);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            newNum = intent.getIntExtra("num", -1);
            if (bottomFragment0 != null) {
                if (newNum >= 0) {
                    if (newNum == 1) {
                        selectedFragment(1);
                        tabSelected(llBottom1);
                    } else if (newNum == 3) {
                        selectedFragment(3);
                        tabSelected(llBottom3);
                    }
                }
            }

        }

    }

    @Override
    public void initData() {
        if (isDestroyed() || isFinishing() || this == null) {
            return;
        }
        //                01  公告管理 02  我的日志 03  资料库 04  学习计划
//                05  我的考试 06  一键面试 07  通讯录 08  个人能力
//                09 我的待办10 发布视频11 发布新闻12发布日志13题库14视频15溯源16发布图文17图文
        navigationCode1 = new ShareUtils().getString(this, StaticClass.BOTTOM_1_CODE, "13");
        navigationName1 = new ShareUtils().getString(this, StaticClass.BOTTOM_1_NAME, "题库");
        navigationCode3 = new ShareUtils().getString(this, StaticClass.BOTTOM_3_CODE, "14");
        navigationName3 = new ShareUtils().getString(this, StaticClass.BOTTOM_3_NAME, "视频");
        tvBottom1.setText(navigationName1);
        if ("01".equals(navigationCode1)) {
            ivBottom1.setBackgroundResource(R.drawable.home_bottom_gonggao);
        } else if ("02".equals(navigationCode1)) {
            ivBottom1.setBackgroundResource(R.drawable.home_bottom_rizhi);
        } else if ("03".equals(navigationCode1)) {
            ivBottom1.setBackgroundResource(R.drawable.home_bottom_docunment);
        } else if ("04".equals(navigationCode1)) {
            ivBottom1.setBackgroundResource(R.drawable.home_bottom_xuexijihua);
        } else if ("05".equals(navigationCode1)) {
            ivBottom1.setBackgroundResource(R.drawable.home_bottom_kaoshi);
        } else if ("06".equals(navigationCode1)) {
            ivBottom1.setBackgroundResource(R.drawable.home_bottom_yijianmianshi);
        } else if ("07".equals(navigationCode1)) {
            ivBottom1.setBackgroundResource(R.drawable.home_bottom_tongxunlu);
        } else if ("08".equals(navigationCode1)) {
            ivBottom1.setBackgroundResource(R.drawable.home_bottom_gerennengli);
        } else if ("15".equals(navigationCode1)) {
            ivBottom1.setBackgroundResource(R.drawable.home_bottom_suyuan);
        } else if ("17".equals(navigationCode1)) {
            ivBottom1.setBackgroundResource(R.drawable.home_bottom_tuwen);
        } else if ("14".equals(navigationCode1) || "19".equals(navigationCode1)) {
            ivBottom1.setBackgroundResource(R.drawable.home_bottom3);
        } else if ("24".equals(navigationCode1)) {
            ivBottom1.setBackgroundResource(R.drawable.home_bottom_knowledge);
        } else if ("26".equals(navigationCode1)) {
            ivBottom1.setBackgroundResource(R.drawable.home_bottom_gallery);
        } else {
            ivBottom1.setBackgroundResource(R.drawable.home_bottom1);
            tvBottom1.setText("题库");
        }
        tvBottom3.setText(navigationName3);
        if ("01".equals(navigationCode3)) {
            ivBottom3.setBackgroundResource(R.drawable.home_bottom_gonggao);
        } else if ("02".equals(navigationCode3)) {
            ivBottom3.setBackgroundResource(R.drawable.home_bottom_rizhi);
        } else if ("03".equals(navigationCode3)) {
            ivBottom3.setBackgroundResource(R.drawable.home_bottom_docunment);
        } else if ("04".equals(navigationCode3)) {
            ivBottom3.setBackgroundResource(R.drawable.home_bottom_xuexijihua);
        } else if ("05".equals(navigationCode3)) {
            ivBottom3.setBackgroundResource(R.drawable.home_bottom_kaoshi);
        } else if ("06".equals(navigationCode3)) {
            ivBottom3.setBackgroundResource(R.drawable.home_bottom_yijianmianshi);
        } else if ("07".equals(navigationCode3)) {
            ivBottom3.setBackgroundResource(R.drawable.home_bottom_tongxunlu);
        } else if ("08".equals(navigationCode3)) {
            ivBottom3.setBackgroundResource(R.drawable.home_bottom_gerennengli);
        } else if ("15".equals(navigationCode3)) {
            ivBottom3.setBackgroundResource(R.drawable.home_bottom_suyuan);
        } else if ("17".equals(navigationCode3)) {
            ivBottom3.setBackgroundResource(R.drawable.home_bottom_tuwen);
        } else if ("13".equals(navigationCode3)) {
            ivBottom3.setBackgroundResource(R.drawable.home_bottom1);
        } else if ("24".equals(navigationCode3)) {
            ivBottom3.setBackgroundResource(R.drawable.home_bottom_knowledge);
        } else if ("26".equals(navigationCode3)) {
            ivBottom3.setBackgroundResource(R.drawable.home_bottom_gallery);
        } else {
            ivBottom3.setBackgroundResource(R.drawable.home_bottom3);
            tvBottom3.setText("视频");
        }
        if (newNum > -1) {
            num = newNum;
        }
        if (num == 1) {
            selectedFragment(1);
            tabSelected(llBottom1);
        } else if (num == 3) {
            selectedFragment(3);
            tabSelected(llBottom3);
        } else {
            selectedFragment(0);
            tabSelected(llBottom0);
        }

        if (!"T002".equals(new ShareUtils().getString(this, StaticClass.THEME_CODE, ""))) {
            registerBoradcastReceiver();
            Observable.timer(800, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) {
                            try {
                                MyApp.initX5();
                                StatService.setAuthorizedState(HomeActivityss.this, true);
                                StatService.start(HomeActivityss.this);
                                MdidSdkHelper.InitSdk(HomeActivityss.this, true, new IIdentifierListener() {
                                    @Override
                                    public void OnSupport(boolean b, IdSupplier idSupplier) {
                                        if (idSupplier != null && idSupplier.isSupported())
                                            StatService.setOaid(HomeActivityss.this, idSupplier.getOAID());
                                    }
                                });
//                                String channel = WalleChannelReader.getChannel(HomeActivityss.this,"official");
                                //获取权限
                                if ("13503825592".equals(new ShareUtils().getString(HomeActivityss.this, StaticClass.USERNAME, ""))||"13300000000".equals(new ShareUtils().getString(HomeActivityss.this, StaticClass.USERNAME, ""))||"小竹体验中心".equals(new ShareUtils().getString(HomeActivityss.this, StaticClass.COMPANYNAME, ""))) {
                                }else{
                                    requestSTORAGE();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
        }
        clearVideoCache();
    }

    private void clearVideoCache() {
        //主要是清除视频的缓存
        if (XJson.getLogCache(this, LogEntity.class).size() == 0 && XJson.getUploadEntity(this, UploadEntity.class).size() == 0) {
            FileUtilss.deleteCacheDir(this);
        }
    }

    @OnClick({R.id.ll_bottom0, R.id.ll_bottom1, R.id.ll_bottom2, R.id.ll_bottom3, R.id.ll_bottom4})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_bottom0:
                if (num == 0 && "T002".equals(new ShareUtils().getString(this, StaticClass.THEME_CODE, ""))) {
                    Intent intent = new Intent(this, HomeKnowledgeActivity.class);
                    intent.putExtra("isFirst", false);
                    startActivity(intent);
                }
                selectedFragment(0);
                tabSelected(llBottom0);
                break;
            case R.id.ll_bottom1:
                selectedFragment(1);
                tabSelected(llBottom1);
                break;
            case R.id.ll_bottom2:
                if (isPublish) {
                    showHomeBottomDialog();
                } else {
                    MyToast.show("暂未配置发布功能，如有需要请联系管理员");
                }
                break;
            case R.id.ll_bottom3:
                selectedFragment(3);
                tabSelected(llBottom3);
                break;
            case R.id.ll_bottom4:
                selectedFragment(4);
                tabSelected(llBottom4);
                break;
        }
    }

    private void requestSTORAGE() {
        XXPermissions.with(this)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        getVersion();
                        }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        checkBdWx();
                    }
                });
    }
    private void getVersion() {
        Map<String, String> map = new HashMap<>();
        map.put("system", "0");
        if (getPackageName().equals("com.zhaofengnum")) {
            map.put("downloadAddress", "zhaofeng");
        }
        MyHttpRequest.getDefault().getRequestCompat(null, Urls.getVersion, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        int versionCode = Utils.changeNumber(jsonObject1.getString("versionCode"));
                        if (versionCode > Utils.getVersionCode(HomeActivityss.this)) {
                            fileUrl = jsonObject1.getString("downloadAddress");
                            fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
                            new UpdateDialog(HomeActivityss.this, jsonObject1.getString("versionName"), jsonObject1.getString("versionDesc"), jsonObject1.getString("updateFlag"), fileUrl,
                                    new ShareDialogListener() {
                                        @Override
                                        public void onClick() {
                                            // 如果是8.0系统
                                            if (Build.VERSION.SDK_INT >= 30) {
                                                InstallLocalApk.install(HomeActivityss.this, new File(getExternalFilesDir(Urls.APKFOLDER), fileName));
                                            } else if (Build.VERSION.SDK_INT >= 26) {
                                                boolean b = getPackageManager().canRequestPackageInstalls();
                                                // 如果已经打开了安装未知来源的开关
                                                if (b) {
                                                    InstallLocalApk.install(HomeActivityss.this, new File(getExternalFilesDir(Urls.APKFOLDER), fileName));
                                                } else {
                                                    // 请求打开安装未知应用来源的界面,非运行时权限
                                                    Uri packageURI = Uri.parse("package:" + getPackageName());
                                                    Intent intents = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                                                    startActivityForResult(intents, GET_UNKNOWN_APP_SOURCES);
                                                }
                                            } else {
                                                InstallLocalApk.install(HomeActivityss.this, new File(getExternalFilesDir(Urls.APKFOLDER), fileName));
                                            }
                                        }
                                    }).show();
                        } else {
                            checkBdWx();
                        }
                    } else {
                        checkBdWx();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    checkBdWx();
                }
            }

            @Override
            public void onError(String errorMsg) {
                checkBdWx();
            }
        });
    }

    private void checkBdWx() {
        if (!isFirst) {
            return;
        }
        if ("T002".equals(new ShareUtils().getString(HomeActivityss.this, StaticClass.THEME_CODE, ""))) {
            return;
        }
        MyHttpRequest.getDefault().postRequestCompat(null, Urls.checkBdWx, SignUtils2.makeSignStr(null), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) throws Exception {
                JSONObject reObject = new JSONObject(data);
                if ("200".equals(reObject.getString("code"))) {
                    JSONObject jsonObject = reObject.getJSONObject("data");
                    if ("1".equals(jsonObject.getString("tanchuang"))) {
                        new ShareUtils().putBoolean(HomeActivityss.this, StaticClass.BIND_WX, false);
                        try {
                            if (!Utils.isNull(jsonObject.getString("imagePath"))) {
                                Glide.with(HomeActivityss.this).asBitmap()
                                        .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC).load(jsonObject.getString("imagePath"))
                                        .into(new SimpleTarget<Bitmap>() {
                                            @Override
                                            public void onResourceReady(@androidx.annotation.NonNull Bitmap resource, @androidx.annotation.Nullable Transition<? super Bitmap> transition) {
                                                try {
                                                    if (resource != null) {
                                                        new HomeAdvertDialog(HomeActivityss.this, resource, jsonObject.getString("longUrl")).show();
                                                    }
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        });
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        new ShareUtils().putBoolean(HomeActivityss.this, StaticClass.BIND_WX, true);
                        new ShareUtils().putLong(HomeActivityss.this, StaticClass.EMPLOYEECODE + "-" + StaticClass.BIND_WX_TIME, 0);

                    }
                } else {
                    MyToast.show(reObject.getString("msg"));
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction("downApk"); // 获取数据
        LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                fileName = intent.getStringExtra("fileName");
                int percent = intent.getIntExtra("percent", 0);
                if (percent == 100) {
                    // 如果是8.0系统
                    if (Build.VERSION.SDK_INT >= 30) {
                        InstallLocalApk.install(HomeActivityss.this, new File(getExternalFilesDir(Urls.APKFOLDER), fileName));
                    } else if (Build.VERSION.SDK_INT >= 26) {
                        boolean b = getPackageManager().canRequestPackageInstalls();
                        // 如果已经打开了安装未知来源的开关
                        if (b) {
                            InstallLocalApk.install(HomeActivityss.this, new File(getExternalFilesDir(Urls.APKFOLDER), fileName));
                        } else {
                            // 请求打开安装未知应用来源的界面,非运行时权限
                            Uri packageURI = Uri.parse("package:" + getPackageName());
                            Intent intents = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                            startActivityForResult(intents, GET_UNKNOWN_APP_SOURCES);
                        }
                    } else {
                        InstallLocalApk.install(HomeActivityss.this, new File(getExternalFilesDir(Urls.APKFOLDER), fileName));
                    }
                }
            }
        }
    };

    private void showHomeBottomDialog() {
        new HomeBottomDialog(this, 0, new HomeBottomDialogListener() {
            @Override
            public void onListItemClick(int position) {
                if (position == 0) {
                    if (Utils.isNull(MyApp.accessKeyId)) {
                        MyToast.show("暂无权限上传视频");
                    } else {
                        requestSTORAGECamer(0);
                    }
                } else if (position == 1) {
                    startActivity(new Intent(HomeActivityss.this, PublishTuwensActivity.class));
                } else if (position == 2) {
                    new HomeBottomDialog(HomeActivityss.this, 1, new HomeBottomDialogListener() {
                        @Override
                        public void onListItemClick(int position) {
                            if (position == 20) {
                                startActivity(new Intent(HomeActivityss.this, PublishNewsActivity.class));
                            } else if (position == 21) {
                                Intent intent = new Intent(HomeActivityss.this, NewsLinkActivity.class);
                                startActivity(intent);
                            } else if (position == 22) {
                                startActivity(new Intent(HomeActivityss.this, TuwenSearchActivity.class));
                            }
                        }
                    }).show();
                } else if (position == 3) {
                    startActivity(new Intent(HomeActivityss.this, PublishLogsActivity.class));
                } else if (position == 4) {
                    startActivity(new Intent(HomeActivityss.this, InvitationRegisterActivity.class));
                } else if (position == 5) {
                    //发图片
                    requestSTORAGECamer(1);
                }
            }
        }).show();
    }

    private void requestSTORAGECamer(int position) {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            if (position == 0) {
                                //视频
                                PictureSelector.create(HomeActivityss.this)
                                        .openGallery(SelectMimeType.ofVideo())
                                        .isDisplayCamera(true)//是否显示相机入口
                                        .setMaxVideoSelectNum(1)
                                        .setMaxSelectNum(1)
                                        .setSelectionMode(SelectModeConfig.SINGLE)//单选
                                        .isPreviewVideo(true)//是否支持预览视频
                                        .setSelectMinFileSize(50)//过滤最小文件50k
                                        .setFilterVideoMaxSecond(600)//过滤最大视频选择600s
                                        .setRecordVideoMaxSecond(30)//过滤录制最大30s
                                        .isFilterSizeDuration(true)//是否过滤图片或音视频大小时长为0的资源
                                        .setRecyclerAnimationMode(AnimationType.SLIDE_IN_BOTTOM_ANIMATION)
                                        .setImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                        .forResult(PictureConfig.REQUEST_CAMERA);
                            } else {
                                //图片
                                PictureSelector.create(HomeActivityss.this)
                                        .openGallery(SelectMimeType.ofImage())
                                        .isDisplayCamera(true)//是否显示相机入口
                                        .setMaxSelectNum(9)
                                        .setSelectionMode(SelectModeConfig.MULTIPLE)//多选
                                        .isPreviewImage(true)//是否支持预览图片
                                        .setCompressEngine(ImageFileCompressEngine.createGlideEngine())
                                        .setRecyclerAnimationMode(AnimationType.SLIDE_IN_BOTTOM_ANIMATION)
                                        .setImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                        .forResult(PictureConfig.CHOOSE_REQUEST);
                            }

                        } else {
                            PermissionUtils.errorPermission(HomeActivityss.this, granted, all);
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(HomeActivityss.this, denied, quick);
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == PictureConfig.REQUEST_CAMERA) {
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(data);
                Intent intent = new Intent(HomeActivityss.this, PublishVedioActivity.class);
                String url = "";
                if (selectList.get(0).getPath().contains("content://")) {
                    Uri uri = Uri.parse(selectList.get(0).getPath());
                    url = PathUtil.getPath(this, uri);
                } else {
                    url = selectList.get(0).getPath();
                }
                intent.putExtra("fileUrl", url);
                KLog.i("fileUrl::" + url);
                KLog.i("原图::" + selectList.get(0).getPath());

                KLog.i("Android Q 特有Path::" + Uri.parse(selectList.get(0).getPath()).toString());
                startActivity(intent);
            } else if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                // 如果是直接从相册获取
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(data);
                ArrayList<String> imgList = new ArrayList<>();
                for (int i = 0; i < selectList.size(); i++) {
                    KLog.i("压缩::" + selectList.get(0).getCompressPath());
                    KLog.i("原图::" + selectList.get(0).getPath());

                    String url = "";
                    if (!Utils.isNull(selectList.get(i).getCompressPath())) {
                        if (selectList.get(i).getCompressPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getCompressPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getCompressPath();
                        }
                    } else {
                        if (selectList.get(i).getPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getPath();
                        }
                    }
                    imgList.add(url);
                    KLog.i("Android Q 特有Path::" + url);
                }
                if (imgList.size() > 0) {
                    Intent intent = new Intent(HomeActivityss.this, PublishGalleryActivity.class);
                    intent.putStringArrayListExtra("imgUrls", imgList);
                    startActivity(intent);
                }
            } else if (requestCode == GET_UNKNOWN_APP_SOURCES) {
                InstallLocalApk.install(HomeActivityss.this, new File(getExternalFilesDir(Urls.APKFOLDER), fileName));
            }
        }
        if (requestCode == 1) {
            //当底部是日志时候 日志筛选所用参数
            if (data != null) {
                if (num == 1 || num == 3) {
                    if (navigationCode1.equals("02") || navigationCode3.equals("02")) {
                        lookLogBaseFragment.setOnActivityResult(data.getStringExtra("startTime"), data.getStringExtra("endTime"), data.getStringExtra("reportType"), (List<ContactEntity>) data.getSerializableExtra("data"));
                    }
                }
            }
        }
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null) {
//                MyToast.show("扫码取消");
            } else {
                String content = result.getContents();
                KLog.i("扫描成功: " + content);
                Intent intent = null;
                if (content.contains("scan?code=")) {
                    String[] codes = content.split("code=");
                    if (codes.length > 1) {
                        getData(codes[1]);
                    } else {
                        MyToast.show("扫描数据异常，请稍后重试");
                    }
                } else if (content.contains("resourceType") && content.contains("resourceId")) {
//                    （1资料，2长视频，3短视频）
//                    扫描成功:resourceType=3&resourceId=b81127c1b7a344729b1b528588b6f479&employeeCode=EMP202109060001
                    String datas[] = content.split("&");
                    if (datas.length > 2) {
                        try {
                            String resourceType = datas[0].split("=")[1];
                            String resourceId = datas[1].split("=")[1];
                            String employeeCode = datas[2].split("=")[1];
                            String localCode = new ShareUtils().getString(HomeActivityss.this, StaticClass.EMPLOYEECODE, "");
                            if (!employeeCode.equals(localCode)) {
                                MyToast.show("请扫描自己后台中的二维码");
                                return;
                            }
                            if (datas.length > 4) {
                                String currentTime = datas[3].split("=")[1];
                                int validLength = Integer.parseInt(datas[4].split("=")[1]);
                                long time = System.currentTimeMillis() - Long.parseLong(currentTime);
                                if (time / 1000 > validLength) {
                                    MyToast.show("二维码已失效，请刷新后重试");
                                } else {
                                    if ("1".equals(resourceType)) {
                                        getDocunmentData(resourceId);
                                    } else if ("2".equals(resourceType) || "3".equals(resourceType)) {
                                        getViedeo(resourceType, resourceId);
                                    }
                                }
                            } else {
                                if ("1".equals(resourceType)) {
                                    getDocunmentData(resourceId);
                                } else if ("2".equals(resourceType) || "3".equals(resourceType)) {
                                    getViedeo(resourceType, resourceId);
                                }
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            MyToast.show("二维码异常，请稍后重试");
                        }
                    }

                } else if (content.startsWith("http")) {
                    intent = new Intent(this, WebCommonActivity.class);
                    intent.putExtra("url", content);
                    startActivity(intent);
                } else {
                    getData(content);
                }

            }
        }
    }

    private void getViedeo(String type, String id) {
        if (!PermissionSpUtils.getBoolean(this, "14", false)) {
            MyToast.show("管理员已关闭视频功能");
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("videoId", id);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<VideoEntity>>() {
        }.getType(), null, Urls.selectAPPVideoById, SignUtils2.makeSignStr(map), false, new ObserverCallback<VideoEntity>() {
            @Override
            public void onSuccess(VideoEntity data) {
                if (Utils.isNull(data.videoId)) {
                    MyToast.show("视频id为空");
                    return;
                }
                new ForScreenDialog(HomeActivityss.this, type, data).show();
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getDocunmentData(String dataCode) {
        if (!PermissionSpUtils.getBoolean(this, "03", false)) {
            MyToast.show("管理员已关闭资料库功能");
            return;
        }
        Map<String, String> allmap = new HashMap<>();
        allmap.put("dataCode", dataCode);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<DocunmentEntity>>() {
        }.getType(), null, Urls.getDetail, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<DocunmentEntity>() {
            @Override
            public void onSuccess(DocunmentEntity data) {
                if (data != null) {
                    new ForScreenDialog(HomeActivityss.this, data).show();
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getData(String loginUid) {
        showLoading();
        Map<String, String> map = new HashMap<>();
        map.put("loginUid", loginUid);
        MyHttpRequest.getRequest(Urls.checkQRStatus, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        Intent intent = new Intent(HomeActivityss.this, LoginQrCodeActivity.class);
                        intent.putExtra("loginUid", loginUid);
                        intent.putExtra("status", jsonObject1.getString("status"));
                        startActivity(intent);
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private void selectedFragment(int position) {
        num = position;
        if (homeBottom == null) {
            return;
        }
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        hideFragment(transaction);
        switch (position) {
            case 0:
                homeBottom.setBackgroundColor(Color.parseColor("#ffffff"));
                line.setVisibility(View.VISIBLE);
                if (bottomFragment0 == null) {
                    if ("T002".equals(new ShareUtils().getString(this, StaticClass.THEME_CODE, ""))) {
                        bottomFragment0 = new HomeKnowledgeFragmentss();
                    } else {
                        bottomFragment0 = new HomeFragmentss();
                    }
                    transaction.add(R.id.content, bottomFragment0);
                } else {
                    transaction.show(bottomFragment0);
                }
                transaction.commitAllowingStateLoss();
                break;
            case 1:
                if ("14".equals(navigationCode1) || "19".equals(navigationCode1)) {
                    if (index == 2) {
                        homeBottom.setBackgroundColor(Color.parseColor("#ffffff"));
                        line.setVisibility(View.VISIBLE);
                    } else {
                        homeBottom.setBackgroundColor(Color.parseColor("#000000"));
                        line.setVisibility(View.GONE);
                    }
                } else {
                    homeBottom.setBackgroundColor(Color.parseColor("#ffffff"));
                    line.setVisibility(View.VISIBLE);
                }
                if (bottomFragment1 == null) {
                    if ("01".equals(navigationCode1)) {
                        bottomFragment1 = new NoticeBaseFragment();
                    } else if ("02".equals(navigationCode1)) {
                        lookLogBaseFragment = new LookLogBaseFragment();
                    } else if ("03".equals(navigationCode1)) {
                        bottomFragment1 = new DocumentBaseFragment();
                    } else if ("04".equals(navigationCode1)) {
                        bottomFragment1 = new StudyPlanBaseFragment();
                    } else if ("05".equals(navigationCode1)) {
                        bottomFragment1 = new TestBaseFragment();
                    } else if ("06".equals(navigationCode1)) {
                        bottomFragment1 = new InterviewBaseFragment();
                    } else if ("07".equals(navigationCode1)) {
                        bottomFragment1 = new ContactsBaseFragment();
                    } else if ("08".equals(navigationCode1)) {
                        bottomFragment1 = new AbilityAnalyzeBaseFragment();
                    } else if ("15".equals(navigationCode1)) {
                        bottomFragment1 = new RankBaseFragment();
                    } else if ("17".equals(navigationCode1)) {
                        bottomFragment1 = new TuwenBaseFragment();
                    } else if ("14".equals(navigationCode1) || "19".equals(navigationCode1)) {
                        bottomFragment1 = new VideoMainFragments(0, index);
                    } else if ("24".equals(navigationCode1)) {
                        bottomFragment1 = new KnowledgeBaseFragment();
                    } else if ("26".equals(navigationCode1)) {
                        bottomFragment1 = new GalleryBaseFragment();
                    } else {
                        bottomFragment1 = new TikuFragments();
                    }
                    if ("02".equals(navigationCode1)) {
                        transaction.add(R.id.content, lookLogBaseFragment);
                    } else {
                        transaction.add(R.id.content, bottomFragment1);
                    }
                } else {
                    if ("02".equals(navigationCode1)) {
                        transaction.show(lookLogBaseFragment);
                    } else {
                        transaction.show(bottomFragment1);
                    }
                }
                transaction.commitAllowingStateLoss();
                break;
            case 2:
                break;
            case 3:
                if (bottomFragment3 == null) {
                    if ("01".equals(navigationCode3)) {
                        bottomFragment3 = new NoticeBaseFragment();
                    } else if ("02".equals(navigationCode3)) {
                        lookLogBaseFragment = new LookLogBaseFragment();
                    } else if ("03".equals(navigationCode3)) {
                        bottomFragment3 = new DocumentBaseFragment();
                    } else if ("04".equals(navigationCode3)) {
                        bottomFragment3 = new StudyPlanBaseFragment();
                    } else if ("05".equals(navigationCode3)) {
                        bottomFragment3 = new TestBaseFragment();
                    } else if ("06".equals(navigationCode3)) {
                        bottomFragment3 = new InterviewBaseFragment();
                    } else if ("07".equals(navigationCode3)) {
                        bottomFragment3 = new ContactsBaseFragment();
                    } else if ("08".equals(navigationCode3)) {
                        bottomFragment3 = new AbilityAnalyzeBaseFragment();
                    } else if ("15".equals(navigationCode3)) {
                        bottomFragment3 = new RankBaseFragment();
                    } else if ("17".equals(navigationCode3)) {
                        bottomFragment3 = new TuwenBaseFragment();
                    } else if ("13".equals(navigationCode3)) {
                        bottomFragment3 = new TikuFragments();
                    } else if ("24".equals(navigationCode3)) {
                        bottomFragment3 = new KnowledgeBaseFragment();
                    } else if ("26".equals(navigationCode3)) {
                        bottomFragment3 = new GalleryBaseFragment();
                    } else {
                        bottomFragment3 = new VideoMainFragments(0, index);
                    }
                    if ("02".equals(navigationCode3)) {
                        transaction.add(R.id.content, lookLogBaseFragment);
                    } else {
                        transaction.add(R.id.content, bottomFragment3);
                    }
                } else {
                    if ("02".equals(navigationCode3)) {
                        transaction.show(lookLogBaseFragment);
                    } else {
                        transaction.show(bottomFragment3);
                    }
                }
                if ("14".equals(navigationCode3) || "19".equals(navigationCode3)) {
                    if (index == 2) {
                        homeBottom.setBackgroundColor(Color.parseColor("#ffffff"));
                        line.setVisibility(View.VISIBLE);
                    } else {
                        homeBottom.setBackgroundColor(Color.parseColor("#000000"));
                        line.setVisibility(View.GONE);
                    }
                } else {
                    homeBottom.setBackgroundColor(Color.parseColor("#ffffff"));
                    line.setVisibility(View.VISIBLE);
                }
                transaction.commitAllowingStateLoss();
                break;
            case 4:
                homeBottom.setBackgroundColor(Color.parseColor("#ffffff"));
                line.setVisibility(View.VISIBLE);
                if (mineFragment == null) {
                    mineFragment = new MineFragment();
                    transaction.add(R.id.content, mineFragment);
                } else {
                    transaction.show(mineFragment);
                }
                transaction.commitAllowingStateLoss();
                break;
            default:
                break;
        }

    }

    private void hideFragment(FragmentTransaction transaction) {
        if (bottomFragment0 != null) {
            transaction.hide(bottomFragment0);
        }
        if (bottomFragment1 != null) {
            transaction.hide(bottomFragment1);
        }
        if (bottomFragment3 != null) {
            transaction.hide(bottomFragment3);
        }
        if (mineFragment != null) {
            transaction.hide(mineFragment);
        }
        if (lookLogBaseFragment != null) {
            transaction.hide(lookLogBaseFragment);
        }
    }

    private void tabSelected(LinearLayout linearLayout) {
        llBottom0.setSelected(false);
        llBottom1.setSelected(false);
        llBottom3.setSelected(false);
        llBottom4.setSelected(false);
        linearLayout.setSelected(true);
    }

    private long lastBackPressedTime = 0L;

    @Override
    protected void onRestart() {
        super.onRestart();
        if (num == 1 || num == 3) {
            if (navigationCode1.equals("01") || navigationCode3.equals("01")) {
                EventBus.getDefault().post(new MyEvent("NoticeBaseFragment"));
            } else if (navigationCode1.equals("03") || navigationCode3.equals("03")) {
                EventBus.getDefault().post(new MyEvent("RefreshDocumentFragment"));
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (AppStatusManager.getInstance().getAppStatus() == AppStatus.STATUS_RECYVLE&&!MyApp.isSplash) {
            //应用已经死了跳到闪屏页
            MyApp.isSplash = true;
            Intent intent = new Intent(this, SplashActivity.class);
            intent.putExtra("type", 1);
            startActivity(intent);
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        long time = System.currentTimeMillis();
        if (time - lastBackPressedTime < 2000) {
            MyApp.exitApp();
        } else {
            MyToast.show("再按一次退出程序");
            lastBackPressedTime = time;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
            if (map.containsKey("HomeBottom") && map.containsKey("code")) {
                String code = map.get("code");
                if (code.equals(navigationCode1)) {
                    selectedFragment(1);
                    tabSelected(llBottom1);
                } else {
                    selectedFragment(3);
                    tabSelected(llBottom3);
                }
            }
            if ("01".equals(navigationCode1) || "01".equals(navigationCode3)) {
                if (map.containsKey("HomeBottom") && map.containsKey("num")) {
                    int num = Integer.parseInt(map.get("num"));
                    if (num > 99) {
                        num = 99;
                    }
                    if ("01".equals(navigationCode1)) {
                        if (num > 0) {
                            tvNumBottom1.setText(num + "");
                            tvNumBottom1.setVisibility(View.VISIBLE);
                        } else {
                            tvNumBottom1.setText("");
                            tvNumBottom1.setVisibility(View.GONE);
                        }
                    } else {
                        if (num > 0) {
                            tvNumBottom3.setText(num + "");
                            tvNumBottom3.setVisibility(View.VISIBLE);
                        } else {
                            tvNumBottom3.setText("");
                            tvNumBottom3.setVisibility(View.GONE);
                        }
                    }
                }
            }
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("HomeVedioBottom2")) {
                //视频模块课程
                index = 2;
                if ("14".equals(navigationCode1) || "19".equals(navigationCode1)) {
                    selectedFragment(1);
                    tabSelected(llBottom1);
                } else {
                    selectedFragment(3);
                    tabSelected(llBottom3);
                }
            } else if (msg.equals("HomeVedioBottom1")) {
                //视频模块小视频
                index = 1;
                if ("14".equals(navigationCode1) || "19".equals(navigationCode1)) {
                    selectedFragment(1);
                    tabSelected(llBottom1);
                } else {
                    selectedFragment(3);
                    tabSelected(llBottom3);
                }
            } else if (msg.equals("HomeBottom_Tiku")) {
                //跳转题库
                if ("13".equals(navigationCode3)) {
                    selectedFragment(3);
                    tabSelected(llBottom3);
                } else {
                    selectedFragment(1);
                    tabSelected(llBottom1);
                }
            } else if (msg.equals("HomeRecord")) {
                showHomeBottomDialog();
            } else if (msg.equals("HomeBottom0")) {
                selectedFragment(0);
                tabSelected(llBottom0);
            } else if (msg.equals("HomeBottom1")) {
                selectedFragment(1);
                tabSelected(llBottom1);
            } else if (msg.equals("HomeBottom3")) {
                selectedFragment(3);
                tabSelected(llBottom3);
            } else if (msg.equals("PublishPermissions_No")) {
                //没有发布权限
                Glide.with(this).load(GlideUtils.loadLogoId(this)).into(llBottom2Iv);
                isPublish = false;
            } else if (msg.equals("PublishPermissions_Yes")) {
                //拥有发布权限
                Glide.with(this).load(R.drawable.add).into(llBottom2Iv);
                isPublish = true;
            } else if (msg.equals("HomeOver")) {
                finish();
            } else if (msg.equals("HomeReleasedVideo")) {
                //发布视频
                requestSTORAGECamer(0);
            } else if (msg.equals("HomeReleasedGallery")) {
                //发布图库
                requestSTORAGECamer(1);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBroadcastReceiver != null && this != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
        }
    }

    @Override
    public void onFragmentInteraction(int select) {
        if (homeBottom == null) {
            return;
        }
        if (num == 3 || num == 1) {
            index = select;
            if (index == 2) {
                homeBottom.setBackgroundColor(Color.parseColor("#ffffff"));
                line.setVisibility(View.VISIBLE);
            } else {
                homeBottom.setBackgroundColor(Color.parseColor("#000000"));
                line.setVisibility(View.GONE);
            }
        }
    }


}
